package pl.edu.agh.persdoc.schedule;


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;



@Component
public class ScheduleDeserializer {

	/**
	 * 
	 * @param json representing exam schedule
	 * @return list of scenario objects that schedule passed as parameter consists of
	 */
	public List<Scenario> deserializeToSchedule(String json){
		
		Map<String,List<Box>> scenariosNamesAndBoxesLists=deserializeToMap(json);
		List<Scenario> schedule = convertToSortedScenarios(scenariosNamesAndBoxesLists);
		return schedule;
		
	}
	
	private Map<String,List<Box>> deserializeToMap(String json){
		
		Type listType = new TypeToken<Map<String,List<Box>>>() {}.getType();
		Map<String,List<Box>> map= new Gson().fromJson(json,listType);
		return map;
		
	}
	
	private List<Scenario> convertToSortedScenarios( Map<String,List<Box>> map){
		
		TreeMap<String, List<Box>> sortedScenarios = new TreeMap<String,List<Box>>(map);
		List<Scenario> result=new ArrayList<Scenario>();
		for(String scenarionName:sortedScenarios.keySet()){
			result.add(new Scenario(sortedScenarios.get(scenarionName)));
		}
		return result;
		
	}
	
}
